package com.xuecheng.content.service;

import cn.hutool.core.io.IoUtil;
import com.xuecheng.content.config.MinioTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Map;

@Service
public class PubPageService {

    @Autowired
    private Configuration configuration;

    @Autowired
    private MinioTemplate minioTemplate;


    // 制作html，保存minio
    @Async  // 开启一个新线程
    public void pubPage(Map map,Long coursePubId) throws IOException, TemplateException {
        System.out.println("异步线程："+Thread.currentThread().getId());

        try {
            // 模拟 速度很慢的状态
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        // 6.freemarker生成静态化html
        // 6-1 获取指定模板对象
        Template template = configuration.getTemplate("learing_article.ftl");
        // 6-2 生成html
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);

        // 7.保存到minio
        // ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
        ByteArrayInputStream byteArrayInputStream = IoUtil.toStream(content.getBytes());

        minioTemplate.uploadHtml(byteArrayInputStream, coursePubId +".html");
    }
}
